package com.astersoft.lib.cypher.crypt.impl;

/*
 * Copyright 2012 AsterSoft personal developer - Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import com.astersoft.lib.cypher.codec.Base64;
import com.astersoft.lib.cypher.crypt.Encryptable;

/**
 * An AES implementation of the Encryptable interface.
 * With this class we can provide AES cypher
 * 
 * <p>
 * This class is used to encode and decode file using the AES
 * encryption algorithm
 * <p>
 * 
 * @see Encryptable
 * 
 * @author dario durzo
 * @version 0.1
 * @date 29-05-2012
 */
public class AESEncrypter 
implements Encryptable {

	// internal cyphers
	private Cipher ecipher;
	private Cipher dcipher;

	// 8-byte Salt
	private byte[] salt = {
		(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
		(byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
	};
	private static byte[] iv = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 
											0x5, 0x6, 0x7, 0x8, 0x9, 
											0xA, 0xB, 0xC, 0xD, 0xE, 0xF };

	// Iteration count
	private final int iterationCount = 19;
	private final int KEYLEN_BITS = 128;
	private final int MAX_FILE_BUF = 1024;

	@Override
	public void initCypher(String passPhrase) {
		try {
			SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
			KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, KEYLEN_BITS);
			SecretKey tmp = factory.generateSecret(spec);
			SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
			
			ecipher = Cipher.getInstance ("AES/CBC/PKCS5Padding");
			ecipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(iv));
			
			dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");  
			dcipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
		} catch (javax.crypto.NoSuchPaddingException e) {
		} catch (java.security.NoSuchAlgorithmException e) {
		} catch (java.security.InvalidKeyException e) {
		} catch (InvalidKeySpecException e) {
		} catch (InvalidAlgorithmParameterException e) {
		}
	}

	@Override
	public void encrypt(InputStream in, OutputStream out) {
		try {
			@SuppressWarnings("unused")
			long totalread = 0;
			int nread = 0;
			byte [] inbuf = new byte [MAX_FILE_BUF];

			while ((nread = in.read (inbuf)) > 0 )
			{
				totalread += nread;

				// create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
				// and results in full blocks of MAX_FILE_BUF being written. 
				byte [] trimbuf = new byte [nread];
				for (int i = 0; i < nread; i++)
					trimbuf[i] = inbuf[i];

				// encrypt the buffer using the cipher obtained previosly
				byte [] tmp = ecipher.update(trimbuf);

				// I don't think this should happen, but just in case..
				if (tmp != null)
					out.write (tmp);
			}

			// finalize the encryption since we've done it in blocks of MAX_FILE_BUF
			byte [] finalbuf = ecipher.doFinal();
			if (finalbuf != null)
				out.write (finalbuf);

			out.flush();
			in.close();
			out.close();
			out.close ();
		} catch(IOException ioe) {
		} catch (IllegalBlockSizeException e) {
		} catch (BadPaddingException e) {
		}
	}

	@Override
	public void decrypt(InputStream in, OutputStream out) {
		try {
			CipherInputStream cin;
			@SuppressWarnings("unused")
			long totalread = 0;
			int nread = 0;
			byte [] inbuf = new byte [MAX_FILE_BUF];
	
			// creating a decoding stream from the FileInputStream above using the cipher created from setupDecrypt()
			cin = new CipherInputStream(in, dcipher);
	
			while ((nread = cin.read(inbuf)) > 0 ) {
				totalread += nread;
	
				// create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
				byte [] trimbuf = new byte [nread];
				for (int i = 0; i < nread; i++)
					trimbuf[i] = inbuf[i];
	
				// write out the size-adjusted buffer
				out.write(trimbuf);
			}
	
			out.flush();
			cin.close();
			in.close ();       
			out.close();   
		} catch(IOException ioe) {
		}
	}

	@Override
	public String encrypt(String input) {
		byte[] enc = null;
		try {
			enc = ecipher.doFinal(input.getBytes());
		} catch (IllegalBlockSizeException e) {
		} catch (BadPaddingException e) {
		}
		
		return new String(Base64.encode(enc));
	}

	@Override
	public String decrypt(String input) {
		try {
			byte[] encypted = Base64.decode(input);
			byte[] decrypted = dcipher.doFinal(encypted);  
			return new String(decrypted);
		} catch(Exception e) {
			
		}
		return null;
	}

	/**
	 * Main test point
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args)
	throws Exception {
		AESEncrypter en = new AESEncrypter();
		en.initCypher("pippononlosa");
		
		String input = "ciaoMondo!";
		String output;
		output = en.encrypt(input);
		System.out.println("encrypt = " + output);
		output = en.decrypt(output);
		System.out.println("decrypt = " + output);
	}

}
